package com.zjp.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.zjp.common.core.config.RocketMQConfig;
import com.zjp.common.enums.OrderStatusEnum;
import com.zjp.common.mapper.OrderMapper;
import com.zjp.common.pojo.Order;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;


@Component
@RocketMQMessageListener(topic = "${rq.delayOrderTopic}", consumerGroup = "${rocketmq.producer.group}", messageModel = MessageModel.CLUSTERING)
public class DelayOrderListener implements RocketMQListener<MessageExt> {
    private static final Logger logger = LoggerFactory.getLogger(DelayOrderListener.class);

    @Autowired
    RocketMQConfig rocketMQConfig;
    @Autowired
    OrderMapper orderMapper;

    @Override
    public void onMessage(MessageExt messageExt) {
        try {
            String str = StrUtil.str(messageExt.getBody(), StandardCharsets.UTF_8);
            Order order = JSONUtil.toBean(str, Order.class);
            OrderStatusEnum orderStatusEnum = OrderStatusEnum.selectEnum(order.getOrderStatus());
            Long orderId = order.getOrderId();
            logger.info("开始处理订单请求-{}", DateUtil.now());
            logger.info("订单号-{}", orderId);
            logger.info("下单时间-{}", DateUtil.formatDateTime(order.getAddTime()));
            logger.info("订单状态-{}", orderStatusEnum.getName());
            if (ObjectUtil.notEqual(OrderStatusEnum.two, orderStatusEnum)) {
                logger.info("开始--删除订单-{}", orderId);
                if (orderMapper.deleteById(orderId) == 1) {
                    logger.info("--删除订单-成功--");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
